using FluentValidation;
using FluentValidation.AspNetCore;
using Mapster;
using MapsterMapper;
using System.Reflection;
using System.Text.Json;
using Todo.DAO.Dapper;
using TodoListWebApi.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

IMvcBuilder mvcBuilder = builder.Services.AddControllers();

// 配置JSON
mvcBuilder.AddJsonOptions(options => options.JsonSerializerOptions.UseGlobal());
builder.Services.Configure<JsonSerializerOptions>(options => options.UseGlobal());



// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddSingleton<IDbConnectionFactory, DbConnectionFactory>();
builder.Services.AddScoped<TodoRepository>();



// 配置MapsterMapper
var typeAdapterConfig = TypeAdapterConfig.GlobalSettings;
typeAdapterConfig.Default
    .NameMatchingStrategy(NameMatchingStrategy.IgnoreCase) // 处理大小写问题，类似知识库[1]中的URL小写策略
    .PreserveReference(true) // 处理循环引用
    .IgnoreNullValues(true)
    .MaxDepth(3); // 提前编译映射，避免运行时编译开销

//typeAdapterConfig.NewConfig<TodoItemDBEntity, TodoModel>()
//            .Map(dest => dest.CreatedDate, src => src.CreatedAt);
typeAdapterConfig.Apply([new MappingConfig()]);

// 注册到DI容器
builder.Services.AddSingleton(typeAdapterConfig);
builder.Services.AddScoped<IMapper, ServiceMapper>();
// 
typeAdapterConfig.Compile();


// 配置FluentValidation
Assembly assembly = Assembly.GetExecutingAssembly();
builder.Services.AddFluentValidationAutoValidation()
    .AddFluentValidationClientsideAdapters()
    .AddValidatorsFromAssembly(assembly);



var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();